<template>

        <div v-if="isshow">
            <!-- 面包屑 -->
            <el-breadcrumb separator="/" class="breadxie">
                <el-breadcrumb-item :to="{ path: '/' }" class="Homer">Home</el-breadcrumb-item>
                <el-breadcrumb-item :to="{path:`/article/${Categorypath}`}" class="articler">{{Categoryof}}
                </el-breadcrumb-item>
                <el-breadcrumb-item>{{Articlename}}</el-breadcrumb-item>
            </el-breadcrumb>
            <!-- 使用v-html不会渲染scope的内容,要用:deep()来解决问题  -->
            <div id="write">
                <div v-html="HtmlContext" v-highlight></div>
            </div>

            <div class="comment" v-loading="flag" ref="mao">
                <div style="display:flex;justify-content:center;font-size:2rem;font-weight: 550;cursor: default;">
                    <i style="margin-right:.3rem"><img :src="mesicon"></i>留言
                </div>
                <div class="comment-login">
                    <div style="margin-right:1rem;display: flex;align-items: center;justify-content: center;">
                        <img :src="userimgsrc" style="width:2.5rem;height:2.5rem;border-radius:50%;" v-show="true">
                    </div>
                    <div class="login-input" style="margin-right:2rem">
                        <div>昵称：</div>
                        <div>
                            <el-input :maxlength="11" v-model="qqnum" placeholder="必填,enter键确定" @change="oo">
                            </el-input>
                        </div>
                    </div>

                    <div class="login-input">
                        <div>邮箱：</div>
                        <div>
                            <el-input v-model="email" placeholder="必填"></el-input>
                        </div>
                    </div>
                </div>
                <div class="text">
                    <el-input type="textarea" :show-word-limit="true" :placeholder="pl" v-model="commentmsg" :rows="4"
                        :maxlength="300"></el-input>
                    <div style="display:flex;justify-content:flex-end;margin-top: .4rem;">
                        <el-button type="primary" :disabled="cansend" @click="sendcomment">发送</el-button>
                    </div>
                </div>

                <div style="border-bottom: 1px solid  rgba(0,0,0,.15);width: 12rem;margin: 0 auto;"> </div>

                <div class="comment-list">
                    <div style="font-size:1.4rem;display: flex;justify-content: space-between;padding-bottom: 1rem;">
                        <div style="padding-left:1rem">当前留言数 ：<span style="font-weight:550 ;">{{lenofComment}}</span>
                        </div>

                        <div><img :src="refresh" style="cursor: pointer;width: 1.5rem;height: 1.5rem;"
                                :style="refreshing" @click="freshing"></div>

                    </div>
                    <div v-for="item in CommentList" :key="item.ID" class="list">
                        <!-- 头 -->
                        <div style="display:flex;">
                            <img :src="item.User.avatar"
                                style="border-radius: 50%;width: 2.5rem;height: 2.5rem /* 40px -> 2.5rem */;margin-right: .5rem;">
                            <div style="font-weight: 550;opacity: .75;font-size:.9rem">{{item.User.username}} <span
                                    style="font-size:.7rem">：</span>
                            </div>
                        </div>
                        <!-- 身 -->
                        <div style="margin-top:-1rem;padding-left: 3.2rem;max-width:43rem;word-wrap:break-word;">
                            {{item.context}}
                        </div>
                        <!-- 尾 -->
                        <div
                            style="padding-left:3.2rem;font-size: .7rem;opacity: .8;padding-top: 1.1rem;padding-bottom: .5rem;border-bottom: 1px solid rgba(0,0,0,.1);">
                            {{ctime(item.CreatedAt)}}
                        </div>
                    </div>
                </div>
                <!-- 分页状态栏 -->
                <div class="pagination" v-if="pageNum>1?true:false">
                    <el-button type="success" :icon="DArrowLeft" plain circle :disabled="pagenum==1?true:false"
                        @click="tocomment('last')">
                    </el-button>
                    <div class="pagination-btn">
                        <div v-for="item in pageNum" class="pagination-btn-item" :style="showindex(item)" :key="item"
                            @click="tocomment(item)">
                            {{item}}
                        </div>
                    </div>
                    <el-button type="primary" :icon="DArrowRight" plain circle :disabled="pagenum==pageNum?true:false"
                        @click="tocomment('next')">
                    </el-button>
                </div>
            </div>
        </div>



</template>

<!------------------------------>

<script setup lang="ts">
import {DArrowRight,DArrowLeft} from '@element-plus/icons-vue'
import refresh from '../../assets/svg/refresh.svg?url'
import usericon from '../../assets/svg/user-defaulticon.svg?url'
import mesicon from '../../assets/svg/message-icon.svg?url'
import { useCounterStore } from '@/stores/counter';
import { storeToRefs } from 'pinia';
import { marked } from 'marked';
import axios from 'axios';
const global=getCurrentInstance()
const route = useRoute()
const router=useRouter()
const pl=ref<string>(
`昵称：输入QQ号，将自动拉取你的信息作为账户登录
邮箱：通过QQ号获取，也可以自由填写，但是不允许重复`)

//Flag:时间计算
let ctime=computed(()=>{
    return function(time :string){
        let day=time.split('T').at(0)
        let hour=time.split('T').at(1)?.split('+').at(0)?.split('.').at(0)
        return `${day} ${hour}`
    }
})
//Flag:页数计算
let pageNum=computed<number>(()=>{
    return Math.ceil(lenofComment.value/10) 
})
//Flag:当前评论显示
let showindex=(index :number)=>{
        if (index==pagenum.value){
        return 'color: white;background-color:rgb(131,191,115) ; '
    }
        else return ''
}
//Flag:评论跳转

let mao=ref()//开启锚点
const tocomment=(key :number|string)=>{
    if(key=='next'){
        pagenum.value++
    }else if (key=='last'){
        pagenum.value--
    }else{
        pagenum.value=key as number
    }
    getComment(true)
}   


//Flag:刷新行为
const refreshing=ref<string>()
const freshing=()=>{
    refreshing.value='transform: rotate(720deg);transition: all .8s ease-in-out;'
    setTimeout(()=>{
    refreshing.value=''
    },800)
    pagenum.value=1
    getComment()
}

//Flag:用户数据获取
let qqnum=ref<string>()
let email=ref<string>()
let commentmsg=ref<string>()
let userimgsrc=ref<string>(usericon)
let regexqq :RegExp=/^[1-9][0-9]{4,10}$/;
let regexemali:RegExp=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
const  oo=()=>{
    if(qqnum.value || email.value){
        if (regexqq.test(qqnum.value as string) || regexemali.test(email.value as string))
        {
            if (qqnum.value){
                //API:拉取QQ信息
                axios.get(`https://tenapi.cn/qqname/?qq=${qqnum.value}`).then((res)=>{
                    if (res.data.code!=200){
                        ElMessage.warning({
                            message:res.data.msg,
                            center:true
                        })
                        return
                    }
                    userimgsrc.value=res.data.imgurl
                    qqnum.value=res.data.name
                    email.value=res.data.mail
                    //这里还不是真正的用户信息,所以先不存locals
                },()=>{
                    ElMessage.warning({
                        message:'QQ信息获取失败,请重试',
                        center:true
                    })
                })
                return
            }
        }
    }
    ElMessage.warning({
        message:'请输入正确的QQ信息',
        center:true
    })
}
//Flag:评论发送
const cansend=computed(()=>{
    if(!commentmsg.value){
        return true
    }
    return false
})
//
let flag=ref<boolean>(false)  //节流
const sendcomment=()=>{
    if(!flag.value){
    if(regexemali.test(email.value as string) && qqnum.value ){
        flag.value=true
        global?.proxy?.$axios.post(`/v1/postcomment/${Articleid}`,{
            username:qqnum.value,
            email:email.value,
            context:commentmsg.value,
            imgurl: userimgsrc.value==usericon ? "NULL" : userimgsrc.value
        }).then((res:any)=>{
            if (res.data.status==200){
                ElMessage.success({
                    message:"发送成功"
                })
                commentmsg.value=''
                localStorage.setItem('username',qqnum.value as string)
                localStorage.setItem('email',email.value as string)
                localStorage.setItem('imgurl',userimgsrc.value as string)
                getComment()
            }
        }).finally(()=>{
                flag.value=false
        })
    }else{
        ElMessage.warning({
            message:'填入信息不正确,请重试',
            center:true
        })
    }
    }
}
//Flag:预登录功能
onBeforeMount(()=>{
if (localStorage.getItem('username') && localStorage.getItem('email') && localStorage.getItem('imgurl'))
{
    qqnum.value=localStorage.getItem('username') as string
    email.value=localStorage.getItem('email') as string
    userimgsrc.value=localStorage.getItem('imgurl') as string
}})

//Flag:组件动画渲染 
let isshow = ref<boolean>(false)
onMounted(() => {
    isshow.value = true
})

//Flag:动画监听
let Store = useCounterStore()
let { Animation } = storeToRefs(Store)
watch(() => { return Animation.value }, () => {
    isshow.value = false
})
//Flag:markdown配置
marked.setOptions({
    gfm: true,//默认为true。 允许 Git Hub标准的markdown.
    breaks: false,//默认为false。 允许回车换行。该选项要求 gfm 为true。
    pedantic: false,//默认为false。 尽可能地兼容 markdown.pl的晦涩部分。不纠正原始模型任何的不良行为和错误。
    sanitize: false,//对输出进行过滤（清理）
    smartLists: true,
    smartypants: true//使用更为时髦的标点，比如在引用语法中加入破折号。
});

//Flag:获取数据
const HtmlContext = shallowRef()
let Categoryof =ref<string>()   //文章分类
let Categorypath=ref<string>()
let  Articleid :number  //文章id
let CommentList=ref() //评论数组
let lenofComment=ref<number>(0)   //总评论数
let Articlename=ref<string>()   //文章名
let pagenum=ref<number>(1)
global?.proxy?.$axios.get(`/v1/getnumofcomment/${route.params.id}`).then((len :any)=>{
    if (len?.data.status==200)
    lenofComment.value=len.data.data 
})




//API:拉取文章信息
global?.proxy?.$axios.get(`/v1/getonearticle/${route.params.id}`).then((res) => {
    if (res.data.status == 200) { 
        Articleid= res.data.data.ID
        HtmlContext.value = marked(res.data.data.context)
        switch(res.data.data.categoryname){
            case 'Golang':
                Categorypath.value='go'
                break;
            case '前端' :
                Categorypath.value='web'
                break;
            case '闲聊':
                Categorypath.value='chat'
                break;
            default:
                Categorypath.value='other'
        }
        Categoryof.value=res.data.data.categoryname
        Articlename.value=res.data.data.article
    }else if (res.data.status==410){
        router.replace('/404')
    }
})
//API :拉取评论信息:分开来以好实时更新评论数据
const getComment=(m ?: boolean)=>{
global?.proxy?.$axios.get(`/v1/getcommentofarticle/${route.params.id}/${pagenum.value}`).then((res)=>{
    if (res.data.status==200 &&  res.data.data){
        CommentList.value=res.data.data
        if(m)
        mao.value?.scrollIntoView()
    }
})    
}
getComment()



</script>

<!------------------------------>

<style scoped lang="scss"  >












.breadxie{
    .Homer{
        font-size: 1.4rem;
    }
    .articler{
        font-size: 1.3rem;
    }
    font-size: 1.2rem;
    max-width: 1080px;
    margin: 0 auto;
    padding-left: .3rem;
    padding-top: 1rem;
    padding-bottom: 1rem;
}

#write {
    max-width: 1080px;
    padding: 1.25rem;
    margin-bottom: 5rem !important;
    // margin-top: 3.125rem !important;
    box-shadow: 0 2px 4px rgb(5 10 15 / 5%), 0 7px 13px -3px rgb(5 10 15 / 30%);
    margin: 0 auto;
    background-color: white;
    border-radius: .5rem;
}

/* 终极解决方案 */
#write :deep(*) {
    @import '../../assets/scss/g2.scss';
}

.comment {
    padding: 2rem;
    background-color: rgba(255,255,255,.94);
    max-width: 1080px;
    margin: 0 auto;
    border-radius: .5rem;

    .comment-login {
        max-width: 45rem;
        margin: 0 auto;
        border-top: 1px solid rgba(0, 0, 0, .2);
        padding-top: 1.2rem;
        display: flex;
        justify-content: center;

        .login-input {
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }

    .text {
        margin-top: 1rem !important;
        max-width: 45rem
            /* 720px -> 45rem */
        ;
        margin: 0 auto;
        margin-bottom: 2rem !important;
    }

    .comment-list {
        margin-top: 4rem !important;
        max-width: 45rem
            /* 720px -> 45rem */
        ;
        margin: 0 auto;

        .list {
            padding-top: 1.5rem !important;
            padding: 1rem;
            min-height: 6.25rem
                /* 100px -> 6.25rem */
            ;
        }
    }
}

.pagination{
    padding-right: 2rem;
    padding-left: 2rem;
    height: 4rem;
    margin: 0 auto;
    padding-top: 2rem;
    max-width: 720px;
    // background-color: pink;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    .pagination-btn{
        flex-grow: 1;
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
        & :hover{
            color: white;
            background-color: rgb(51, 119, 170);            
        }
        .pagination-btn-item{
            padding-left: .35rem;
            padding-right: .35rem;
        }
    }
}
</style>